//
//  GetCatTableViewController.m
//  YinHang
//
//  Created by 123 on 14-8-15.
//  Copyright (c) 2014年 孙彦鹏. All rights reserved.
//

#import "GetCatTableViewController.h"

@interface GetCatTableViewController ()
{
    CatListService *cls_;
    
    MBProgressHUD *loadHud;
}
@end

@implementation GetCatTableViewController

/**
 为了保证内部不泄露，在dealloc中释放占用的内存
 */
- (void)dealloc
{
    NSLog(@"MJTableViewController--dealloc---");
}

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.title = @"选择类别";
    [self customLeftBarButtonItem];
    
    if (MAIN_VERSION >= 7) {
        self.tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
    }
    
    self.tableView.rowHeight = 48;
    
    // 隐藏tableview多余的分割线
    [self setExtraCellLineHidden:self.tableView];
    
    
    
    /* 请求相应的选择类别数据 */
    // 初始化服务类
    cls_ = [[CatListService alloc]init];
    cls_.delegate = self;
    
    cls_.selectedIndex = self.selectedTag;
    
    // 请求第一页数据
    cls_.pageInfo.pageno = @"1";
    [cls_ pageQueryWithSelectedIndex:_selectedTag];
    
    // 提示正在加载数据...
    loadHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    loadHud.labelText = @"正在加载数据，请稍后...";
    
    
    // 集成刷新控件
    [self setupRefresh];
}

// 自定义LeftBarButtonItem
- (void)customLeftBarButtonItem {
    
    UIButton *leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 30)];
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSpacer.width = - 10;
    if (ios7) {
        self.navigationItem.leftBarButtonItems = @[negativeSpacer,leftBarButtonItem];
    }else{
        self.navigationItem.leftBarButtonItems = @[leftBarButtonItem];
    }
    
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refresh)];
    self.navigationItem.rightBarButtonItem.enabled = NO;
}

// 请求失败后重新请求
- (void)refresh {
    // 请求第一页数据
    cls_.pageInfo.pageno = @"1";
    [cls_ pageQueryWithSelectedIndex:_selectedTag];
    
    // 提示正在加载数据...
    loadHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    loadHud.labelText = @"正在加载数据，请稍后...";
}

// 隐藏tableview多余的分割线
-(void)setExtraCellLineHidden: (UITableView *)tableView
{
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor clearColor];
    [tableView setTableFooterView:view];
}

/**
 *  集成刷新控件
 */
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    /* 自动刷新(一进入程序就下拉刷新) */
    //[self.tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
}

#pragma mark 开始进入刷新状态
//下拉刷新
- (void)headerRereshing
{
    // 检查网络
    if (cls_.isQuery || ![Constants isExistenceNetwork]) {
        
        // 刷新表格
        [self.tableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.tableView headerEndRefreshing];
        
        return;
    }
    
    // 下拉刷新 （请求第一页数据）
    
    // 每次必须重置下 否则会数据混乱
    cls_.pageInfo.pageno = @"1";
    [cls_ pageQueryWithSelectedIndex:_selectedTag];
}

// 上提分页
- (void)footerRereshing
{
    // 检查网络
    if (![Constants isExistenceNetwork]) {
        
        // 刷新表格
        [self.tableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.tableView footerEndRefreshing];
        
        return;
    }
    
    // 如果正在查询 或 没有更多数据了
    if (cls_.isQuery || !cls_.pageInfo.hasMoreData) {
        // 2. 1秒后刷新表格UI
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 刷新表格
            [self.tableView reloadData];
            
            // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
            [self.tableView footerEndRefreshing];
            
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.labelText = @"没有更多数据了";
            [hud hide:YES afterDelay:1];
        });
        
        return;
    }
    
    // 如果还有更多数据 请求下一页
    [cls_.pageInfo nextPage];
    [cls_ pageQueryWithSelectedIndex:_selectedTag];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    if (cls_.pageInfo.dataArr.count != 0) {
        return cls_.pageInfo.dataArr.count;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (!cell) {
        
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    cell.backgroundColor = [UIColor clearColor];
    
    if (cls_.pageInfo.dataArr.count != 0) {
        cell.textLabel.text = cls_.pageInfo.dataArr[indexPath.row][@"tname"];
    }
    
    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    [self.delegate showCat:cell.textLabel.text Tid:cls_.pageInfo.dataArr[indexPath.row][@"tid"] SelectedIndex:indexPath.row];
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - QuestionService Delegate
// 请求成功
- (void)didRecieveData{
    [loadHud hide:YES];
    self.navigationItem.rightBarButtonItem.enabled = YES;
    
    [self.tableView headerEndRefreshing];
    [self.tableView footerEndRefreshing];
    [self.tableView reloadData];
}

// 请求失败
- (void)didRecieveMsg{
    [loadHud hide:YES];
    self.navigationItem.rightBarButtonItem.enabled = YES;
    
    [self.tableView headerEndRefreshing];
    [self.tableView footerEndRefreshing];
}


// 返回
- (void)back {
    // 取消请求
    [cls_ cancelRequest];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
